using System.Reflection;
using UnityEditor;
using UnityEngine;

namespace Super
{
	[CustomPropertyDrawer(typeof(ButtonAttribute))]
	public class ButtonAttributeDraw : PropertyDrawer
	{
		public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
		{
			ButtonAttribute buttonAttribute = (ButtonAttribute)attribute;
			GUIStyle style = new GUIStyle(GUI.skin.button);
			style.fixedWidth = buttonAttribute.btnWidth;
			string btnText = string.IsNullOrEmpty(property.stringValue) ? label.text : property.stringValue;
			if (GUI.Button(position, btnText, style))
			{
				if (property.propertyType != SerializedPropertyType.String)
				{
					Debug.Log($"请将{property.serializedObject.targetObject}->{label.text}改成string类型");
				}

				BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic;
				MethodInfo method = property.serializedObject.targetObject.GetType().GetMethod(buttonAttribute.methodName, bindingFlags);

				if (method != null)
				{
					method.Invoke(property.serializedObject.targetObject, null);
					string info = $"执行{property.serializedObject.targetObject}->{buttonAttribute.methodName}方法";
					Debug.Log(info);
				}
				else
				{
					string info = $"{property.serializedObject.targetObject}未找到对应的{buttonAttribute.methodName}方法";
					Debug.LogError(info);
				}
			}
		}

		public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
		{
			return 25f;
		}

		#region 2021版本不支持
		//public override VisualElement CreatePropertyGUI(SerializedProperty property)
		//{
		//	VisualElement root = new VisualElement();
		//	Button button = new Button();
		//	button.key = property.displayName;
		//	button.RegisterCallback<ClickEvent>(evt => BtnOnClick(property));
		//	root.Add(button);
		//	return root;
		//}

		//public void BtnOnClick(SerializedProperty property)
		//{
		//	ButtonAttribute buttonAttribute = (ButtonAttribute)attribute;
		//	BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic;
		//	MethodInfo method = property.serializedObject.targetObject.GetType().GetMethod(buttonAttribute.methodName, bindingFlags);
		//	if (method != null)
		//	{
		//		method.Invoke(property.serializedObject.targetObject, null);
		//	}
		//	else
		//	{
		//		string info = $"{property.serializedObject.targetObject}未找到对应的{buttonAttribute.methodName}方法";
		//		Log.Log(info);
		//	}
		//}
		#endregion
	}
}
